package com.fanketly.funacg2.ui.viewmodels

import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.fanketly.funacg2.App
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.model.CollectModel
import com.fanketly.funacg2.data.model.WorkList
import com.fanketly.funacg2.data.paging.FavouritePagingSource
import com.fanketly.funacg2.data.repo.FavouriteRepo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import javax.inject.Inject
var isFavouriteChange = false

@HiltViewModel
class FavouriteViewModel @Inject constructor(private val repo: FavouriteRepo) : ViewModel() {

    //    val uiState: StateFlow<List<WorkEntity>> =
//        getAll().stateIn(
//            scope = viewModelScope,
//            started = SharingStarted.WhileSubscribed(5000), initialValue = emptyList()
//        )
    val pager: Flow<PagingData<CollectModel>> = Pager(
        PagingConfig(
            pageSize = 20, initialLoadSize = 20, enablePlaceholders = true, maxSize = 200
        )
    ) {
        FavouritePagingSource(repo)
    }.flow.cachedIn(viewModelScope)

    init {
        Log.d(TAG, "FavouriteViewModel_init")
    }

    private val _isFavourite by lazy { mutableStateOf(false) }
    val isFavourite: Boolean
        get() = _isFavourite.value


    fun checkFavourite(id: Int) {
        viewModelScope.launch {
            //请求过程中出现错误为false
            val favourite = kotlin.runCatching {
                repo.isFavourite(id).success
            }.getOrElse { false }
            Log.i(TAG, "checkFavourite: $favourite")
            _isFavourite.value = favourite
        }
    }

    /**
     *@return  true为喜爱false为取消
     * */
    fun favouriteOrCancel(work: WorkList.Work): Boolean {
        return if (_isFavourite.value) {
            cancelFavourite(work.id) {
                isFavouriteChange = true
            }
            _isFavourite.value = false
            false
        } else {
            favourite(work)
            _isFavourite.value = true
            true
        }
    }

    private fun favourite(work: WorkList.Work) {
        viewModelScope.launch {
            repo.insert(
                CollectModel(
                    work.id, work.title, work.img240,
                    null, App.sUsername
                )
            )
        }
    }

    fun cancelFavourite(id: Int, onEnd: () -> Unit) {
        viewModelScope.launch {
            repo.delete(id)
            onEnd()
        }
    }
}